/*
* created by Administrator on 2018/11/30
* 好的代码像粥一样,是得用时间和精力熬的。
*/
const Mock = require('mockjs');
const models = require('../database/model'); //数据库
const querystring = require('querystring');
const request = require('request'); //发送http请求
const Router = require('koa-router');   //路由中间件
const router = new Router();
router.get('/repeat', async (ctx, next) => {
    Mock.mock({
        "data|10000": [{
            username: '@cname',
            gender: '@boolean',
            age: '@integer(16,30)',
            phoneNumber: /^1[35789]\d{9}$/,
            city: '@city',
            password: /^[A-Z]\w{9,15}$/
        }]
    }).data.forEach(async (v) => {
        await models.User.create(v)
            .then(data => {
                console.log(data);
            })
            .catch(error => {
                console.log(error)
            })
    })
});
router.get('/validCodeMsg', async (ctx, next) => {
    let {phoneNumber} = ctx.request.query; //es6 解构赋值
    if (phoneNumber && /^1[35789]\d{9}$/.test(phoneNumber)) {
        function random() {
            return parseInt(Math.random() * 1000000) + '';
        }

        let code = random();
        ctx.session.user = {
            code: code,
            tel: phoneNumber
        };
        const querydata = querystring.stringify({
            mobile: phoneNumber,
            tpl_id: 117376,
            tpl_value: '#code#=' + code,
            key: '098612e22e290c18262c3a8b48d7edb5'
        });
        let url = `http://v.juhe.cn/sms/send?${querydata}`;
        let ajax = async (url) => {
            return new Promise((resolve, reject) => {
                request(url, (error, res, body) => {
                    let code = JSON.parse(body);
                    console.log(code);
                    console.log('====================================');
                    console.log(code.error_code);
                    console.log('====================================');
                    if (code.error_code === 0) {
                        resolve(code);
                    } else {
                        reject(code);
                    }
                })
            })
        };
        await ajax(url).then(() => {
            ctx.body = {
                code: 1,
                msg: `验证码已经发送到+86${phoneNumber}`
            };
        }).catch(() => {
            ctx.body = {
                code: -1,
                msg: '验证码发送失败'
            }
        })
    }
    await next();
});
router.get('/valid', async (ctx, next) => {
    let {code} = ctx.request.query; // es6 赋值解构
    if (ctx.session.user) {
        if (ctx.session.user.code === code) {
            ctx.body = {
                code: 1,
                msg: '注册成功，写入数据'
            }
        } else {
            ctx.body = {
                code: -1,
                msg: '验证码错误'
            }
        }
    } else {
        ctx.body = {
            code: -1,
            msg: '请先输入手机号'
        }
    }
    await next();
});
router.get('/login', async (ctx, next) => {
    let {username, password} = ctx.request.query;
    if (username === 'admin' && password === '123456') {
        ctx.session.user = {username, password};
        ctx.body = {
            code: 1,
            msg: '登录成功'
        }
    } else {

    }
    await next();
});
router.get('/test', async (ctx, next) => {
    if (ctx.session.user) {
        ctx.body = {
            code: 1,
            msg: '你来过'
        }
    } else {
        ctx.body = {
            code: -1,
            msg: '请登录'
        }
    }
    await next();
});
router.get('/unlogin', async (ctx, next) => {
    if (ctx.session.user) {
        ctx.session.user = null;
        ctx.body = {
            code: 1,
            msg: '退出登录成功'
        }
    } else {
        ctx.body = {
            code: -1,
            msg: '你是不是傻'
        }
    }
    await next();
});
/*router.get('/reg', async (ctx, next) => {
    let {username, password, phoneNumber} = ctx.request.query;
    if (username && password && phoneNumber) {
        console.log(ctx.request.query);
        await models.User.create({username, password, phoneNumber})
            .then(data => {
                ctx.body = {
                    code: 1,
                    msg: '注册成功',
                    data
                }
            })
            .catch(error => {
                    ctx.body = {
                        code: 1,
                        msg: '注册失败',
                        error
                    }
                }
            );
    } else {
        ctx.body = {
            code: -1,
            msg: '数据不合格',
        }
    }
    await next();
});*/
router.get('/search', async (ctx, next) => {
    let {searchText} = ctx.request.query;
    searchText !== '' && await models.User.find({
        $or: [
            {username: new RegExp(searchText)},
            {phoneNumber: new RegExp(searchText)},
            {city: new RegExp(searchText)}
            ]
    }).limit(100)
        .then((data) => {
            console.log(data);
            ctx.body = {
                code: 1,
                msg: '成功',
                data
            }
        })
        .catch((error) => {
            console.log(error);
            ctx.body = {
                code: -1,
                msg: '搜索失败',
                data:[]
            }
        });
    await  next();
});
router.post('/article',async (ctx, next)=>{
/*  let {title, content ,date ,favorite}=ctx.request.body;*/
  let mockData =Mock.mock({
      'data|1000':[{
          title:"@csentence(8,18)",
          content:"@cparagraph(100,500)",
          date:()=>new Date().getTime(),
          favorite:'@integer(10,10000)',
          author:'@guid'
      }]
  }).data;
    /* save一次只能插入一条数据
      await new models.Article(MockData[0])
    .save().
    then(data=>console.log(data)).
    catch(error=>console.log(error));*/
  /*  insertMany插入多条数据
  await models.Article.insertMany(mockData)
      .then(data=>console.log(data))
      .catch(error=>console.log(error));*/
  await models.Article.create(mockData).then(data=>{
      ctx.body={
          code:1,
          msg:'文章保存成功',
          data
      }
  }).catch(error=>{
      ctx.body={
          code:-1,
          msg:'文章保存失败',
          error
      }
  });
  /*查询数据*/
  //  $gte:大于等于
  await models.Article.find({
      favorite:{$gte:9000,$lte:15000,$ne:12000},
      date:{$nin:['']}
  }).select('favorite date author username')
      .then(data=>console.log(data))
      .catch(error=>console.log(error));
  await next();
  await models.Article.findByTitle('')
});
module.exports = app => app.use(router.routes());
